#include "BiboFrame.h"
#include "SimpleAudioEngine.h"
#define T_DUR 1.0f
#define T_OFFSET 1000
USING_NS_CC;

CCScene* BiboFrame::scene()
{
	// 'scene' is an autorelease object
	CCScene *scene = CCScene::create();

	// 'layer' is an autorelease object
	BiboFrame *layer = BiboFrame::create();

	// add layer as a child to scene
	scene->addChild(layer);

	// return the scene
	return scene;
}
cocos2d::CCArray* BiboFrame::equipmentArray;
cocos2d::CCArray* BiboFrame::antiObjectsArray;
cocos2d::CCArray* BiboFrame::sprites;
cocos2d::CCArray* BiboFrame::m4aEffectListFile;
cocos2d::CCArray* BiboFrame::spriteChildNeedUpdateLifeTimeArray;
cocos2d::CCArray* BiboFrame::soundIDsLoopArr;
cocos2d::CCLabelTTF* BiboFrame::recordLabel;
cocos2d::CCSize BiboFrame::winSize;

float BiboFrame::realCurrentSecond;
float BiboFrame::numCountBySecond;
float BiboFrame::timeTracing;
float BiboFrame::scalePercentY;
float BiboFrame::scalePercentX;
//__in int BiboFrame::previousKeyStateCode;
int BiboFrame::previousKeyStateCode;
bool BiboFrame::init()
{
	//////////////////////////////
	// 1. super init first
	if ( !CCLayer::init() )
	{
		return false;
	}

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	//vo trong hieu
	soundEffectIDWithLoop = 0;
	winSize = cocos2d::CCDirector::sharedDirector()->getWinSize();
	

	//get all files in pre tracing scene usuing relative path
	cocos2d::CCString *path1;
	path1 = cocos2d::CCString::create("TrungThuScene/");

	previousKeyStateCode = 0;
	//NSFileManager *filemgr;

	//filemgr = [NSFileManager defaultManager];
	background = new CCMySprite();
	background = (CCMySprite *)CCMySprite::create("0.0.0.0.png");
	background->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
	this->addChild(background,0,0);

	int a = background->boundingBox().size.width;
	int b = winSize.width;
	scalePercentX = ((float)winSize.width/background->getTextureRect().size.width);
	scalePercentY = ((float)winSize.height/background->getTextureRect().size.height);

	//RECORD MARK
	record = 0;//will read from plist data file.
	recordLabel = cocos2d::CCLabelTTF::create();recordLabel->retain();
	recordLabel->initWithString(CCString::createWithFormat("%d",record)->m_sString.c_str(),"VNI-Whimsy",20);
	recordLabel->setString(CCString::createWithFormat("%d",record)->m_sString.c_str());
	recordLabel->setPosition(ccp(30*BiboFrame::scalePercentX,winSize.height*0.96));
	this->addChild(BiboFrame::recordLabel);
	

	//*retain*/
	sprites = cocos2d::CCArray::create();sprites->retain();
	equipmentArray = cocos2d::CCArray::create();equipmentArray->retain();
	m4aEffectListFile = cocos2d::CCArray::create();m4aEffectListFile->retain();
	soundIDsLoopArr = cocos2d::CCArray::create();soundIDsLoopArr->retain();
	spriteChildNeedUpdateLifeTimeArray = cocos2d::CCArray::create();spriteChildNeedUpdateLifeTimeArray->retain();
	antiObjectsArray = cocos2d::CCArray::create();antiObjectsArray->retain();
	///
	flag = true;
	///
	idAptMin = idAptMax = 0;
	///
	isAlreadyInit = false;
	///
	timeTracing = 0;
	//

	//SOUND EFFECT
	currentFXSoundID = -1;
	//INIT SPRITES ARRAY
	BiboFrame::initSpriteArrWithDir1(sprites,"1.main.plist");
	/*[self initSpriteArrWithDir1:@"TrungThuScene/":sprites];
	[self initSpriteArrWithDir1:@"equipments/":equipmentArray];

	[self addChild:[self searchForSpriteById:10:sprites] z:0];

	//SHOW ON SCREEN second by second
	realCurrentSecond = 0;
	[self schedule:@selector(updateShowingInitScreen:) interval:1];//        [self showAlphabetSetNearAlphabetID];*/
	BiboFrame::realCurrentSecond = 0;
	totalTrackingPoint = 0;
	currentIdSequence = 0;
	return true;
}

void BiboFrame::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
	CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	exit(0);
#endif
#endif
}

cocos2d::CCArray* BiboFrame::componentsSeparatedByString(string _string, const char *delimiter)
 {
     cocos2d::CCArray* result = new cocos2d::CCArray();
     
     int cutAt;
     while( (cutAt = _string.find_first_of(delimiter)) != _string.npos )
     {
         if(cutAt > 0)
         {
             result->addObject(cocos2d::CCString::create(_string.substr(0, cutAt)));
         }
         _string = _string.substr(cutAt + 1);
     }
     
     if(_string.length() > 0)
     {
         result->addObject(cocos2d::CCString::create(_string));
     }
     
     return result;
 }

void BiboFrame::initSpriteArrWithDir1(cocos2d::CCArray* tmpArray, string plistName)
{
	cocos2d::CCDictionary *m = cocos2d::CCDictionary::createWithContentsOfFile(plistName.c_str());
	cocos2d::CCDictionary *mainDict = m;
	int tRoot = mainDict->allKeys()->count();
	cocos2d::CCString* csRoot = ((cocos2d::CCString*)mainDict->allKeys()->objectAtIndex(0));
	string sRoot = csRoot->m_sString;
	tmpArray->removeAllObjects(); 
    cocos2d::CCString *sfileName;
    CCMySprite *sprite = new CCMySprite();
	cocos2d::CCDictionary* tmpDict;
	//tmpDict = (cocos2d::CCDictionary*)mainDict->objectForKey("6");
	//string sNameS = tmpDict->valueForKey("name")->m_sString;
	int t = mainDict->count();
	int i = 0;
	do 
	{
		cocos2d::CCString *key = (cocos2d::CCString *)mainDict->allKeys()->objectAtIndex(i);
		string sKey = key->m_sString;
		tmpDict = (cocos2d::CCDictionary*)mainDict->objectForKey(cocos2d::CCString::createWithFormat("%d",i)->m_sString);

		//sprite = (CCMySprite *)CCMySprite::create(c);
		string sName = tmpDict->valueForKey("name")->m_sString;
		const char* cName = sName.c_str();
		sprite = (CCMySprite *)CCMySprite::create(cName);
		CCArray *arrString = BiboFrame::componentsSeparatedByString(sName,".");
		cocos2d::CCString *sTemp = (cocos2d::CCString*)arrString->objectAtIndex(0);
		int ident = atoi(sTemp->m_sString.c_str());
		sprite->setScaleX(BiboFrame::scalePercentX);
		sprite->setScaleY(BiboFrame::scalePercentY);

		arrString = BiboFrame::componentsSeparatedByString(tmpDict->valueForKey("position")->m_sString,".");
		sTemp = (cocos2d::CCString*)arrString->objectAtIndex(0);
		cocos2d::CCString *sTemp2 = (cocos2d::CCString*)arrString->objectAtIndex(1);
		cocos2d::CCPoint pos = ccp(atof(sTemp->m_sString.c_str()),atof(sTemp2->m_sString.c_str()));
		if(ident==70)
		{

			int t70 = 1;
		}
		sprite->setLifeTime(0);
		sprite->setPosition(BiboFrame::calPosition(sprite,pos));
		sprite->setPreviousPosition(sprite->getPosition());
		sprite->setID(ident);        

		tmpArray->addObject(sprite);     
		//[self initAnimationOfSprite:sprite :[NSString stringWithFormat:@"%d",ident]:[NSString stringWithFormat:@"%@animation",path]];
		i++;
	} while (i<mainDict->allKeys()->count());
}
 
CCMySprite* BiboFrame::searchForSpriteById(int ident,cocos2d::CCArray* tmpArray)
{
	CCMySprite *sp = (CCMySprite*)CCMySprite::create();
	int t = tmpArray->count();
	for(int i=0;i<tmpArray->count();i++)
	{
		sp = (CCMySprite*)tmpArray->objectAtIndex(i);
		if(sp->getID()== ident)
		{
			return sp;
		}
	}
	return sp;
}
cocos2d::CCArray* BiboFrame::searchForChildrenByTag(cocos2d::CCArray *idArray)
{
	cocos2d::CCArray *arr = cocos2d::CCArray::create();
	CCMySprite *sp;
	CCObject *ob;
	CCArray *tmpArray;
	for(int i=0;i<this->getChildrenCount();i++)
	{
		ob = this->getChildren()->objectAtIndex(i);
		if(dynamic_cast<CCMySprite*>(ob))
		{
			sp = (CCMySprite*)ob;
			CCRect r = sp->boundingBox();
			for(int j=0;j<idArray->count();j++){
				CCMySprite *idSP = (CCMySprite*)idArray->objectAtIndex(j);
				if(sp->getTag() == idSP->getID()){
					arr->addObject(sp);
					break;
				}
			}
		}
	}
	return arr;
}
cocos2d::CCArray* BiboFrame::searchForChildrenByTag(int ident)
{
	cocos2d::CCArray *arr = new cocos2d::CCArray();
	CCMySprite *sp;
	CCObject *ob;
	CCArray *tmpArray;
	for(int i=0;i<this->getChildrenCount();i++)
	{
		ob = this->getChildren()->objectAtIndex(i);
		if(dynamic_cast<CCMySprite*>(ob))
		{
			sp = (CCMySprite*)ob;
			if( sp->getTag() == ident){
				arr->addObject(sp);
			}
			
		}
	}
	return arr;
}
cocos2d::CCArray* BiboFrame::searchForSpritesById(int ident)
{
	cocos2d::CCArray *arr = new cocos2d::CCArray();
	CCMySprite *sp;
	
	for(int i=0;i<BiboFrame::sprites->count();i++)
	{
		sp = (CCMySprite*)BiboFrame::sprites->objectAtIndex(i);
		if(sp->getID() == ident)
		{
			arr->addObject(sp);
		}
	}
	return arr;
}

/*CCMySprite* BiboFrame::duplicatteASprite(CCMySprite* sp1)
{
	CCMySprite *sp2 = (CCMySprite*)CCMySprite::createWithTexture(sp1->getTexture());
	sp2->setScaleX(sp1->getScaleX());
	sp2->setScaleY(sp1->getScaleY());
	sp2->setID(sp1->getID());
	sp2->setPosition(sp1->getPosition());
	return sp2;
}*/
BiboFrame::BiboFrame()
{

}
BiboFrame::~BiboFrame()
{
	if(soundIDsLoopArr)
	{
		soundIDsLoopArr->release();
		soundIDsLoopArr = NULL;
	}
	if(sprites){
		sprites->release();
		sprites = NULL;
	}
	if(equipmentArray)
	{
		equipmentArray->release();
		equipmentArray = NULL;
	}
	if(antiObjectsArray)
	{
		antiObjectsArray->release();
		antiObjectsArray = NULL;
	}
	if(spriteChildNeedUpdateLifeTimeArray)
	{
		spriteChildNeedUpdateLifeTimeArray->release();
		spriteChildNeedUpdateLifeTimeArray = NULL;
	}
	if(recordLabel){
		recordLabel ->release();
		recordLabel = NULL;
	}
	if(m4aEffectListFile){
		m4aEffectListFile->release();
		m4aEffectListFile = NULL;
	}
}




cocos2d::CCPoint BiboFrame::calPosition(CCMySprite* sprite, CCPoint designViewPosition)
{
	cocos2d::CCPoint kq = designViewPosition;


	float x = kq.x;
	float y = kq.y;
	if(BiboFrame::scalePercentX==BiboFrame::scalePercentY)
	{
		float xx = sprite->boundingBox().size.width;
		kq = ccp(x +((sprite->getContentSize().width*BiboFrame::scalePercentX)/2), BiboFrame::winSize.height-(y +((sprite->getContentSize().height*BiboFrame::scalePercentY)/2)));
	}else
	{//iphone, iphone ret 3.5
		//        kq = CGPointMake(x*(scalePercentX) +(sprite.boundingBox.size.width/2), winSize.height-(y*(scalePercentY) +(sprite.boundingBox.size.height/2)));
		float xx = sprite->getContentSize().width*sprite->getScaleX();
		float s1 = BiboFrame::scalePercentX;
		float s2 = BiboFrame::scalePercentY;
		float ccs = CC_CONTENT_SCALE_FACTOR();
		float w = sprite->getContentSize().width*BiboFrame::scalePercentX;
		float h = sprite->getContentSize().height*BiboFrame::scalePercentY;
		kq = ccp(x*BiboFrame::scalePercentX/ccs + w/2, (BiboFrame::winSize.height-(y*BiboFrame::scalePercentY/ccs + h/2)));
	}

	return kq;
}
cocos2d::CCArray* BiboFrame::generatePlayerLives(int liveSpriteID, int total)
{
	CCArray *kq = CCArray::create();
	CCMySprite *spA,*spB;
	spA = BiboFrame::searchForSpriteById(liveSpriteID,BiboFrame::sprites);
	for(int i=0;i<total;i++)
	{
		spB = new CCMySprite();
		spB->copyValue(spA);
		spB->setScaleX(spA->getScaleX()*0.5);
		spB->setScaleY(spA->getScaleY()*0.5);
		CCPoint pos = ccp(BiboFrame::winSize.width - spB->boundingBox().size.width/2 - i*(spB->boundingBox().size.width*0.9)
			,BiboFrame::winSize.height - spB->boundingBox().size.height/2);
		spB->setPosition(pos);
		kq->addObject(spB);
	}
	return kq;
}

int BiboFrame::getRandomNum(int max,int min){
	int kq = rand()%(max-min + 1) + min;
	return kq;
}

void BiboFrame::doScaleEffect(CCMySprite* sp,float iDruration,float scaleNumX,float scaleNumY,int iTimes)
{
	float oldScaleX = sp->getScaleX();
	float oldScaleY = sp->getScaleY();
	CCScaleTo *sca1 = CCScaleTo::create(iDruration,scaleNumX,scaleNumY);
	CCScaleTo *sca2 = CCScaleTo::create(iDruration,oldScaleX,oldScaleY);
	CCSequence *seqScale = CCSequence::create(sca1,sca2, NULL);
	if(iTimes==0)
	{
		sp->runAction(CCRepeatForever::create(seqScale));
	}else
	{
		sp->runAction(CCRepeat::create(seqScale,iTimes));
	}
}
void BiboFrame::doRotate360Effect(CCMySprite* sp,float iDuration,int iTimes)
{
	CCRotateTo* rotLeft = CCRotateTo::create(iDuration/2,180);
	CCRotateTo *rotRight = CCRotateTo::create(iDuration/2,360);
	CCRotateTo *rotBack = CCRotateTo::create(0, 0);
	CCSequence *seq = CCSequence::create(rotLeft, rotRight, rotBack,NULL);
	sp->runAction(CCRepeat::create(seq,iTimes));
}
void BiboFrame::doRotate360Effect(CCMySprite* sp,float iDuration)
{
	CCRotateTo* rotLeft = CCRotateTo::create(iDuration/2,180);
	CCRotateTo *rotRight = CCRotateTo::create(iDuration/2,360);
	CCSequence *seq = CCSequence::create(rotLeft, rotRight,NULL);
	sp->runAction(CCRepeatForever::create(seq));
}

void BiboFrame::removeAllChildrenOutOfScreen()
{
	for(int i=0;i<this->getChildrenCount();i++)
	{
		CCObject *ob = this->getChildren()->objectAtIndex(i);
		if(dynamic_cast<CCMySprite*>(ob)){
			CCMySprite*sp = new CCMySprite();
			sp = (CCMySprite*)ob;
			if(!BiboFrame::boundingBox().intersectsRect(sp->boundingBox())){
				this->removeChild(sp,true);
			}
		}
		
	}
}
void BiboFrame::doShakingEffect(CCMySprite* sp,float iDuration,float fAngle,int iTimes)
{
	float rot = sp->getRotation();
	cocos2d::CCRotateTo* rotL = cocos2d::CCRotateTo::create(iDuration,rot + -fAngle);
	cocos2d::CCRotateTo* rotC = cocos2d::CCRotateTo::create(iDuration,0 + rot) ;
	cocos2d::CCRotateTo* rotR = cocos2d::CCRotateTo::create(iDuration,rot + fAngle);
	cocos2d::CCSequence* seq = cocos2d::CCSequence::create(rotL, rotC, rotR,rotC, NULL);
	cocos2d::CCFiniteTimeAction* actionDone = cocos2d::CCCallFuncN::create(this, callfuncN_selector(BiboFrame::spriteFinished));
	if(iTimes==0)
	{
		sp->runAction(cocos2d::CCRepeatForever::create(seq));
	}else
	{
		sp->runAction(cocos2d::CCSequence::create(cocos2d::CCRepeat::create(seq,iTimes),actionDone,NULL));
	}
}

void BiboFrame::spriteFinished(CCNode* sender)
{
	CCSprite *sprite = (CCSprite *)sender;
	sprite->setRotation(0);
}

void BiboFrame::updateShowingInitScreen(float dt)
{
	
}